package com.base.component.app.push.fcm;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;

import com.base.component.app.push.bo.PushBO;
import com.base.component.app.push.bo.PushIdBO;
import com.base.component.app.push.bo.PushListBO;
import com.base.component.app.push.core.PushHandler;
import com.gitee.magic.core.exception.ApplicationException;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.messaging.BatchResponse;
import com.google.firebase.messaging.FirebaseMessaging;
import com.google.firebase.messaging.FirebaseMessagingException;
import com.google.firebase.messaging.Message;
import com.google.firebase.messaging.MulticastMessage;

/**
 * https://firebase.google.cn/docs/admin/setup?hl=zh-cn
 * 
 * @author start
 */
public abstract class FcmBase<P extends PushBO> implements PushHandler<P> {

	@Value("${google.credentials.fcm.account}")
	private String accountPath;
	
	public void init() throws Exception {
		ClassPathResource cpr=new ClassPathResource(accountPath);
        FirebaseOptions options = FirebaseOptions.builder()
                .setCredentials(GoogleCredentials.fromStream(cpr.getInputStream()))
                .build();
        FirebaseApp.initializeApp(options);
	}
	
	public Map<String,String> converterToMap(Map<String,Object> params){
		Map<String,String> p=new HashMap<>();
		for(String k:params.keySet()) {
			p.put(k, String.valueOf(params.get(k)));
		}
		return p;
	}
	
	public void push(PushListBO p) {
		MulticastMessage message = MulticastMessage.builder()
//				.setNotification(Notification.builder()
//				        .setTitle(p.getTitle())
//				        .setBody(p.getBody())
//				        .build())
			    .putAllData(converterToMap(p.getParams()))
			    .addAllTokens(p.getTokenIds())
			    .build();
		try {
			BatchResponse response = FirebaseMessaging.getInstance().sendEachForMulticast(message);
			System.out.println("Successfully sent message: " + response);
		} catch (FirebaseMessagingException e) {
			throw new ApplicationException(e);
		}
	}

	public void push(PushIdBO p) {
		Message message = Message.builder()
//				.setNotification(Notification.builder()
//			        .setTitle(p.getTitle())
//			        .setBody(p.getBody())
//			        .build())
			    .putAllData(converterToMap(p.getParams()))
				.setToken(p.getTokenId())
				.build();
		try {
			String response = FirebaseMessaging.getInstance().send(message);
			System.out.println("Successfully sent message: " + response);
		} catch (FirebaseMessagingException e) {
			throw new ApplicationException(e);
		}
	}
	
	public static void main(String[] args) throws Exception {
		FcmBase<PushIdBO> fcm=new FcmId();
		fcm.accountPath="cert/push_fcm_dn.json";
		fcm.init();
		
		PushIdBO pib=new PushIdBO();
		pib.setTokenId("euqAGWpqRuyAJOlp_awekj:APA91bFJveGdUIVruVqcmROmrNBVQo3VttFngZW44O7tG0lOcqslVQmcBh2h0fFNDOtegJWvXRlxtAqRuY_2csJsE9qdzVpVany4dBRvyNuAH3RGA97eunQ");
		pib.setTitle("这是标题");
		pib.setBody("这是内容");
		Map<String,Object> params=new HashMap<>();
		params.put("type", 4);
		pib.setParams(params);
		fcm.push(pib);
    }

}
